package backtracking.leetcode.medium;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bruin_du
 * @description 所有子集
 * @date 2022/9/4 23:12
 **/
public class OfferII079_Subsets {
    List<List<Integer>> lists = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        // 方法一：通过2^n的方式进行每位数的模拟
        method1(nums);

        // 方法二：通过递归进行模拟
        method2(0, nums);
        return lists;
    }

    private List<List<Integer>> method1(int[] nums) {
        int n = 1 << nums.length;
        for (int mask = 0; mask < n; mask++) {
            list.clear();
            for (int i = 0; i < nums.length; i++) {
                if ((mask & (1 << i)) != 0) {
                    list.add(nums[i]);
                }
            }
            lists.add(new ArrayList<Integer>(list));
        }
        return lists;
    }

    private void method2(int index, int[] nums) {
        if (index == nums.length) {
            lists.add(new ArrayList<>(list));
            return;
        }
        list.add(nums[index]);
        method2(index + 1, nums);
        list.remove(list.size() - 1);
        method2(index + 1, nums);
    }

}
